package table_bank

import (
	"fmt"
	"time"

	"gitee.com/klein-x/biz/model/mysql/table"
	"gitee.com/klein-x/biz/module/db/mysql"
	"gorm.io/gorm"
)

type BankChapter struct {
	ID          string         `gorm:"primaryKey;type:char(36);unique;not null;comment:'ID'"`
	ParentID    string         `gorm:"type:char(36);not null;default:'';comment:'父章节ID, 0表示根节点'"`
	PaperID     string         `gorm:"type:char(36);comment:'试卷ID'"`
	Title       string         `gorm:"type:varchar(255);not null;comment:'章节标题'"`
	Description string         `gorm:"type:text;comment:'章节描述'"`
	Status      string         `gorm:"type:char(1);default:'0';comment:'章节状态, normal 0'"`
	SortOrder   uint           `gorm:"default:0;comment:'排序序号，用于同级章节或小节的排序'"`
	Ancestors   string         `gorm:"type:varchar(512);default:'';comment:'祖级列表，用于快速查询层级结构'"`
	CreatedAt   time.Time      `gorm:"comment:'创建时间'"`
	UpdatedAt   time.Time      `gorm:"comment:'更新时间'"`
	DeletedAt   gorm.DeletedAt `gorm:"comment:'软删除时间'"`
}

func (c *BankChapter) TableName() string {
	return "bank_chapter"
}

func ChapterGetByAncestors(rootID string) (*[]BankChapter, error) {
	db := mysql.GetGlobalDB()
	var chapters []BankChapter
	return table.SelectCheck(&chapters,
		db.Where("ancestors LIKE ?", fmt.Sprintf("%%%s,%%", rootID)).
			Find(&chapters),
	)
}

func ChapterGetByUUID(uuid string) (*BankChapter, error) {
	db := mysql.GetGlobalDB()
	var chapter BankChapter
	return table.SelectCheck(&chapter,
		db.Where("id = ?", uuid).First(&chapter),
	)
}
